package com.yuw.control.userinfo;

import com.yuw.bean.userinfo.UserInfoBean;
import com.yuw.model.userinfo.ModelUserInfo;
import com.yuw.utils.MyUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Enumeration;

/**
 * servlet是一个类处理一个方法路径映射的请求，是类级别的相应；
 * springmvc是方法级别响应，也就是一个方法就可以处理一个客户端请求；
 */
// 注解 -- 省略掉 在web.xml中进行servlet的配置
@WebServlet(name = "ServletUserLogin", value = "/ServletUserLogin")
public class ServletUserLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码格式
//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");
        ////////////////////////////////////
        // 获取表单数据
        String name = request.getParameter("name");
        String pw = request.getParameter("pw");
        System.out.println("yonghuming="+name);
        //获取实体类
        UserInfoBean userInfoBean = MyUtils.getNewInstance(UserInfoBean.class);


        //转化前端from数据
        Enumeration<String> parameterNames = request.getParameterNames();
        if (parameterNames != null){
            while (parameterNames.hasMoreElements()){
                //使用反射

                //获取元素
                String strName = parameterNames.nextElement();
                String value = request.getParameter(strName);
                if (StringUtils.isNotEmpty(value)){
                    try {
                        Field declaredField = userInfoBean.getClass().getDeclaredField(strName);
                        declaredField.setAccessible(true);
                        declaredField.set(userInfoBean,value);
                        System.out.println(userInfoBean.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        // 调用model层进行业务逻辑处理
        boolean isLogined = MyUtils.getNewInstance(ModelUserInfo.class).doLogin(name, pw);
        // 根据结果进行view的控制转发
        if (isLogined) {
            // 登陆成功
            request.getRequestDispatcher("WEB-INF/logined/main.html").forward(request, response);
        } else {
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}
